/**
 * Game main script
 * author: westinyang
 * email: westinyang@qq.com
 * lasttime: 2019-2-21 17:34
 */

var config = {
    type: Phaser.AUTO,
    width: 1366,
    height: 768,
    parent: 'game-wrapper',
    // backgroundColor: '0x999999',
    physics: {
        default: 'arcade',
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

// ====================================================================================================

var game = new Phaser.Game(config);
var cam;
var world;
var player, actor, cursors, debugText, follower, path, curve, graphics, graphics2;
// ...
var map = {width: 1366, height: 768};
var origin = {x: map.width / 2, y: map.height / 2};
var startPoint = new Phaser.Math.Vector2(origin.x, origin.y);
var endPoint = new Phaser.Math.Vector2(960, 640);
var ctrlSpeed = 200;
var points = [ 683, 460, 480, 460, 480, 170, 960, 170, 960, 640 ];
var switchs = {
    zoomCamera: false,      // 是否缩放相机
    showDebugText: true,    // 显示调试信息
    showPathNode: true,     // 显示路径节点
    showMovedTrack: true       // 显示已移动的轨迹（路线过长时出现掉帧的情况，待优化）
};

// ====================================================================================================

function preload ()
{
    this.load.image('map', './assets/image/map2.png');
    this.load.image('player', './assets/image/u10.png');
    this.load.image('actor', './assets/image/u11.png');
    this.load.spritesheet('dragcircle', 'assets/image/dragcircle.png', { frameWidth: 16 });
}

// ====================================================================================================

function create ()
{
    // 相机、游戏世界
    cam = this.cameras.main;
    world = this.physics.world;

    // 设置相机边界、游戏世界边界
    cam.setBounds(0, 0, map.width, map.height);
    world.setBounds(0, 0, map.width, map.height);

    // 缩放相机
    if (switchs.zoomCamera) {
        var camRatio = {w: config.width / map.width, h: config.height / map.height}
        // console.log("camRatio.w: " + camRatio.w + " | camRatio.h: " + camRatio.h);
        cam.setZoom(camRatio.h);
        cam.zoomTo(camRatio.h, 1000);
    }

    // 添加背景图
    this.add.image(0, 0, 'map').setOrigin(0);

    // 输入监听
    cursors = this.input.keyboard.createCursorKeys();

    // 绘制轨迹起点和终点
    var point0 = this.add.image(startPoint.x, startPoint.y, 'dragcircle', 0).setInteractive();
    var point1 = this.add.image(endPoint.x, endPoint.y, 'dragcircle', 0).setInteractive();
    point0.setFrame(1);

    // 绘制路径
    graphics = this.add.graphics();
    graphics2 = this.add.graphics();
    graphics.lineStyle(2, 0x999999, 0.5);
    path = new Phaser.Curves.Path(startPoint.x, startPoint.y);
    path.splineTo(points);
    // path.lineTo(new Phaser.Math.Vector2(origin.x, origin.y));
    path.draw(graphics, 128);
    // ...
    if (switchs.showPathNode) {
        curve = new Phaser.Curves.Spline(points);
        for (var i = 1; i < curve.points.length - 1; i++) {
            var p = curve.points[i];
            // console.log(p);
            graphics.fillStyle(0x999999, 0.5);
            graphics.fillCircle(p.x, p.y, 4);
            // this.add.image(p.x, p.y, 'dragcircle', 0).setInteractive();
        }
    }

    // 创建人物并设置跟随
    actor = this.add.follower(path, startPoint.x, startPoint.y, 'actor');
    actor.setDepth(100);
    actor.setScale(0.25);
    
    
    // 创建玩家
    player = this.physics.add.image(origin.x, origin.y - 100, 'player');
    player.setCollideWorldBounds(true);
    player.setScale(0.25);

    // 创建相机信息文本
    if (switchs.showDebugText) {
        debugText = this.add.text(10, 10, "").setScrollFactor(0).setFontSize(20).setColor('#000000');
    }

    // 相机跟随
    cam.startFollow(actor);

    // 点击任意位置事件，回放/暂停
    this.input.on('pointerdown', function () {
        if (actor.isFollowing() == undefined || actor.state == 0) {
            start();
            return;
        }
        if (actor.isFollowing()) {
            actor.pauseFollow();
        } else {
            actor.resumeFollow();
        }
    });
}

// ====================================================================================================

function update () 
{
    // 更新调试信息
    updateText();
    
    // 更新玩家位置
    updatePlayerPosition();

    // 更新移动过的轨迹
    updateMovedTrack();
}

// ====================================================================================================

function updateText() {
    if (switchs.showDebugText) {
        debugText.setText([
            'CameraScrollX: ' + cam.scrollX.toFixed(2),
            'CameraScrollY: ' + cam.scrollY.toFixed(2),
            'CameraMidX: ' + cam.midPoint.x.toFixed(2),
            'CameraMidY: ' + cam.midPoint.y.toFixed(2),
            'PlayerX: ' + player.x.toFixed(2),
            'PlayerY: ' + player.y.toFixed(2),
            'ActorX: ' + actor.x.toFixed(2),
            'ActorY: ' + actor.y.toFixed(2)
        ]);
    }
}

function updatePlayerPosition() {
    player.setVelocity(0);

    if (cursors.left.isDown)
    {
        player.setVelocityX(-ctrlSpeed);
        player.setFlipX(true);
    }
    else if (cursors.right.isDown)
    {
        player.setVelocityX(ctrlSpeed);
        player.setFlipX(false);
    }

    if (cursors.up.isDown)
    {
        player.setVelocityY(-ctrlSpeed);
    }
    else if (cursors.down.isDown)
    {
        player.setVelocityY(ctrlSpeed);
    }
}

function updateMovedTrack() {
    if (switchs.showMovedTrack && actor.isFollowing()) {
        var point = { t: 0, vec: new Phaser.Math.Vector2(actor.x, actor.y) };
        graphics2.fillStyle(0xff00ff, 0.5);
        graphics2.fillCircle(point.vec.x, point.vec.y, 1);
    }
}

function start() {
    if (actor.state != undefined && actor.state != 0) {
        return;
    }
    actor.state = 1;
    actor.startFollow({
        duration: 20000,
        yoyo: false,
        repeat: 0,
        rotateToPath: false,
        verticalAdjust: true,
        onComplete: function (e) { 
            actor.state = 0;
            actor.pathTween.restart();
            graphics2.clear();
        }
    });
}
